package cn.cyh.org.controller;

import cn.cyh.basic.uitls.AJaxResult;
import cn.cyh.basic.uitls.PageList;
import cn.cyh.org.domain.Department;
import cn.cyh.org.query.DepartmentQuery;
import cn.cyh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    // 新增和修改 put
    @PutMapping
    public AJaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId()==null){ // 如果没有则为添加
                departmentService.save(department);
            } else{ // 否则是修改
                departmentService.update(department);
            }
            return AJaxResult.myself();

        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败");
        }
    }
    // 删除 delete
    @DeleteMapping("/{id}")
    public AJaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return AJaxResult.myself();
        } catch (Exception e) {
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败");
        }
    }

    // 查询 get
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
       return departmentService.loadById(id);
    }

    // 查询所有部门
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.loadAll();
    }

    // 分页查询
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        PageList<Department> departmentPageList = departmentService.queryPage(query);
        return departmentPageList;
    }
    // 批量删除
    @PatchMapping
    public AJaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.patchDelete(ids);
            return AJaxResult.myself();
        } catch (Exception e){
            e.printStackTrace();
            return AJaxResult.myself().setMsg("操作失败");
        }
    }
    // 查询 get
    @GetMapping("/tree")
    public List<Department> Tree(){
        return departmentService.deptTree();
    }

}
